package gudao.red.protobuf;

import com.dyuproject.protostuff.LinkedBuffer;
import com.dyuproject.protostuff.ProtostuffIOUtil;
import com.dyuproject.protostuff.Schema;
import com.dyuproject.protostuff.runtime.RuntimeSchema;
import com.google.common.io.Files;
import com.google.gson.Gson;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;

/**
 * Title:
 * Description:
 * Author:吉
 * Since:2018/4/12
 * Version:1.1.0
 */
public class ProtobuffAndProtoStuffTest {

    /**
     * 反序列化对象
     *
     * @param param 需要反序列化的byte []
     * @param clazz
     * @return 对象
     */
    public static <T> T deSerialize(byte[] param, Class<T> clazz) {
        T object;
        try {
            ByteArrayInputStream inputStream = new ByteArrayInputStream(param);
            long a = System.currentTimeMillis();
            Schema schema = RuntimeSchema.getSchema(clazz);
            System.out.println(System.currentTimeMillis() - a);
            object = (T) schema.newMessage();
            ProtostuffIOUtil.mergeFrom(inputStream, object, schema);
            return object;
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    public static void main(String[] args) throws IOException {
        Person person = ProtobuffAndProtoStuffTest.deSerialize(Files.toByteArray(new File("C:\\Users\\Administrator\\Desktop\\pb.byte")), Person.class);
        System.out.println(new Gson().toJson(person));

        Person person2 = new Person();

        person2.setAge(12);
        person2.setId(1);
        person2.setName("ccf");
        Addr addr = new Addr();
        addr.setCity("shenzhen");
        addr.setContry("china");
        person2.setAddr(addr);



        byte[] bytes = ProtostuffIOUtil.toByteArray(person2, RuntimeSchema.createFrom(Person.class), LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE));
        Files.write(bytes, new File("C:\\Users\\Administrator\\Desktop\\pbstuff.byte"));
        Person person3 = ProtobuffAndProtoStuffTest.deSerialize(bytes, Person.class);
        System.out.println(new Gson().toJson(person3));

    }
}
